package org.lc.cmd.connect.impl.sysreq;

import lombok.extern.slf4j.Slf4j;
import org.lc.cmd.CmdSession;
import org.lc.cmd.ReceivedSysReq;
import org.lc.cmd.TypedSysReqHandler;
import org.lc.cmd.connect.ServerSession;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ClientCloseHandler implements TypedSysReqHandler {
    private static final ScheduledExecutorService scheduledExecutor = new ScheduledThreadPoolExecutor(1);

    @Override
    public String acceptType() {
        return "client_disconnect";
    }

    @Override
    public void handle(ReceivedSysReq req) {
        CmdSession session = req.getSession();
        if (!(session instanceof ServerSession)) {
            return;
        }
        log.info("session {} close by client", session.getId());
        ((ServerSession) session).getServer().removeSession(session.getId());
        scheduledExecutor.schedule(() -> {
            try {
                session.close();
            } catch (IOException ignored) {
            }
        }, 1, TimeUnit.MINUTES);
    }

    @Override
    public int getOrder() {
        return Orders.handler;
    }
}
